<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>指令轮播</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="/VUE/swiper/swiper-bundle.min.css">
    <script src="/VUE/swiper/swiper-bundle.min.js"></script>
    <script src="/VUE/vue2.js"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        .swiper {
            width: 1400px;
            height: 355px;
            margin: 20px auto;
            box-sizing: border-box;
            overflow: hidden;
        }

        .swiper img {
            width: 100%;
            height: 100%;
        }
    </style>
</head>

<body>
<header>导航栏</header>

<div class="swiper" id="box">
    <div class="swiper-wrapper">
        <div v-for="(item,index) in datalist" class="swiper-slide" :key="item" v-swiper="{index:index,length:datalist.length}">
            <img :src="item" alt="">
        </div>
    </div>
    <!-- 如果需要分页器 -->
    <div class="swiper-pagination"></div>
</div>

<footer>底部内容</footer>
</body>
<script>
    Vue.directive("swiper",{
        inserted(el,binding){
            let {index,length} = binding.value
            // 通过指令拿到index和datalist.length，当index === length-1时(也就是最后一个节点渲染完成)，然后再进行初始化swiper，就可以解决初始化过早问题
            if(index === length-1){
                console.log({index,length})
                new Swiper(".swiper", {

                    loop: true, // 循环模式选项

                    // 如果需要分页器
                    pagination: {
                        el: '.swiper-pagination',
                    },

                    //自动轮播
                    autoplay: {
                        delay: 2500,
                        disableOnInteraction: false,
                    },
                })
            }
        },
    })

    let vm = new Vue({
        el: "#box",
        data: {
            datalist: [],
        },

        mounted() {
            setTimeout(() => {
                this.datalist = ["/images/01.jpg", "/images/02.jpg", "/images/03.jpg"]
            }, 2000)
        },

        // updated() {
        //     // 初始化过早
        //     new MySwiper(".swiper", {
        //
        //         loop: true, // 循环模式选项
        //
        //         // 如果需要分页器
        //         pagination: {
        //             el: '.swiper-pagination',
        //         },
        //
        //         //自动轮播
        //         autoplay: {
        //             delay: 2500,
        //             disableOnInteraction: false,
        //         },
        //     })
        // }
    })

    /*
        2. 如果当前页面  状态不止datalist一个，其他状态更新， updated重新运行， new MySwiper 执行多次，会出现bug
     */

</script>
</html>